import axios from 'axios'
import { message } from 'antd'
import { getToken } from './storage'
import store from '@/store'
import { loginLogout } from '@/store/actions/login'
import history from './history'

const instance = axios.create({
  baseURL: 'http://geek.itheima.net/v1_0/',
  timeout: 5000,
})

instance.interceptors.request.use(
  (config) => {
    const token = getToken()
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

instance.interceptors.response.use(
  (response) => {
    return response
  },
  (error) => {
    // 防止网络原因后端没有返回数据，error.response 是 undefined
    if (!error.response) {
      message.error('网络原因', 1)
      // return 一个错误的 Promise
      // 能保证真正发请求的地方也能触发 catch
      return Promise.reject(error)
    }
    if (error.response.status === 401) {
      // 1. 清除 Token
      store.dispatch(loginLogout())
      // 2. 跳转到登录页
      history.replace({
        pathname: '/login',
        state: {
          from: history.location.pathname,
        },
      })
      // !问题：会刷新页面，导致弹框看不到了
      // window.location.href = '/login'
      // 3. 提示
      message.error('TOKEN 超时', 1)
    }
    return Promise.reject(error)
  }
)

export default instance
